package com.example.recyclerviewtest;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.recyclerviewtest.databinding.FragmentHomeBinding;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private static final int UPDATE_UI = 1;
    private RecyclerView recyclerview;
    public List<Map<String,Object>> list = new ArrayList<>();
    private FragmentHomeBinding binding;
    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    private void readJsonData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("lssd","45");
                StringBuilder jsonData = new StringBuilder();
                try {
                    InputStreamReader in = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "json.json"));
                    BufferedReader reader = new BufferedReader(in);
                    String line = null;
                    while((line = reader.readLine()) != null) {
                        jsonData.append(line);
                    }
                    Log.d("lssd","54");
                    jsonJXDate(jsonData);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void jsonJXDate(StringBuilder date) {
        if (date != null) {
            Log.d("lssd","65");
            try {
                JSONArray array = new JSONArray(date.toString());
                Log.d("lssd","68");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    String sortTitle = object.getString("sortTitle");
                    String countryRegionName = object.getString("countryRegionName");
                    String areaCode = object.getString("areaCode");
                    // Log.d("lssd",object.getString("title"));
                    Map<String, Object> map = new HashMap<>();
                    map.put("sortTitle", sortTitle);
                    map.put("countryRegionName", countryRegionName);
                    map.put("areaCode", areaCode);
                    list.add(map);

                }
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATE_UI) {
                Log.d("lssd", "94");
                // 添加分割线
                //recyclerview.addItemDecoration(new DividerItemDecoration(HomeFragment.this, DividerItemDecoration.VERTICAL));
                recy_item_Adapter recy = new recy_item_Adapter(list);
                // 设置布局显示格式
                recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
                recyclerview.setAdapter(recy);
            }
        }
    };

    // 假设有一个方法用于触发UI更新
    public void triggerUIUpdate() {
        Message message = handler.obtainMessage(UPDATE_UI);
        handler.sendMessage(message);
    }

    // 假设有一个方法用于初始化recyclerview和list
    public void initializeRecyclerViewAndList() {
        // 初始化RecyclerView
        recyclerview = binding.recyclerView;
        readJsonData();
    }
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        initializeRecyclerViewAndList();
        triggerUIUpdate();
        return view;
    }
}